package com.ruoyi.kenuo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;

/**
 * @author POLO_TANG
 * @version 1.0.0
 * @ClassName PoloTask
 * @description: TODO
 * @date 2023年06月20日
 */
@Component("poloTask")
public class PoloTask {

    @Autowired
    private JdbcUtils jts;

    @Value(value = "${ruoyi.resourcePath}")
    private String backUpPath;


    /**
     * 数据库备份
     *
     */
    public void tonometerBackupBase()
    {

        // 使用Docker CLI命令进行数据库备份
        String dockerCmd = "nsenter -m -u -i -n -p -t 1 docker exec %s mysqldump -u%s -p%s --databases %s > %s";
        Map<String, String> dbInfo = jts.getDBInfo();
        String username = dbInfo.get("userName");
        String password = dbInfo.get("passWord");
        String database = dbInfo.get("dbName");
        File dataFile = new File(backUpPath  + System.currentTimeMillis() + ".sql");
        // 构建命令字符串
        dockerCmd = String.format(dockerCmd, "polo-mysql", username, password, database, dataFile);

        // 执行命令
        try {
            System.out.println("======开始执行备份命令：======="+dockerCmd);
            Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c", dockerCmd});
            process.waitFor();
            System.out.println("======执行结果值：======="+process.exitValue());
            // 检查备份是否成功
            if (process.exitValue() == 0) {
                System.out.println("数据库备份成功。");
            } else {
                System.err.println("数据库备份失败。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void timeBackupBase()
    {

        System.out.println("执行备份数据库。。。。。。。。。。。。。。。。。。。。。。");
        System.out.println("执行定时器:定时备份数据库。。。。。。。。。。。。。。。。。。。。。。");
        File backUpFile = new File(backUpPath);
        if (!backUpFile.exists()) {
            backUpFile.mkdirs();
        }
        File dataFile = new File(backUpPath  + System.currentTimeMillis() + ".sql");
        //拼接cmd命令
        StringBuffer sb = new StringBuffer();
        Map<String, String> dbInfo = jts.getDBInfo();
        sb.append("mysqldump");
        sb.append(" -u " + dbInfo.get("userName"));
        sb.append(" -p" + dbInfo.get("passWord"));
        sb.append(" " + dbInfo.get("dbName") + " > ");
        sb.append(dataFile);
        System.out.println("======数据库备份cmd命令为：" + sb.toString() + "=======");
        try {
            Process exec = Runtime.getRuntime().exec("cmd /c" + sb.toString());
            if (exec.waitFor() == 0) {
                System.out.println("======数据库备份成功，路径为：" + dataFile + "=======");
            }

        } catch (Exception e) {
            System.out.println("======数据库备份失败，异常为：" + e.getMessage() + "=======");
        }

    }

    /**
     * 定时任务文件删除
     *
     */
    public void timeFileDelete()
    {
        File dirFile = new File(backUpPath);
        if(dirFile.isDirectory()) {
            File[] files1 = dirFile.listFiles();
            /**
             * 倒叙排列
             */
            Arrays.sort(files1,new Comparator<File>(){
                @Override
                public int compare(File fileOne, File fileTwo) {

                    String onem = fileOne.getName().split("\\.")[0];
                    String twom = fileTwo.getName().split("\\.")[0];
                    Long one = Long.valueOf(onem);
                    Long two = Long.valueOf(twom);
                    if(one-two>=0){
                        return -1;
                    }else{
                        return 0;
                    }
                }
            });
            System.out.println(files1);
                for (int i = 0; i < files1.length; i++) {
                    if(i>2){
                        files1[i].delete();
                    }
                }
        }
    }
}
